package com.example;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化时执行的代码
        System.out.println("Filter initialized");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;//强制类型转换
        HttpServletResponse resp = (HttpServletResponse) response;//强制类型转换
        HttpSession session = req.getSession(false);//传入false参数表示如果当前没有会话，则不会创建新的会话，而是返回null。
        boolean loggedIn = session != null && session.getAttribute("loggedIn") != null;//判断是否登录
        if (loggedIn || req.getRequestURI().endsWith("login")

                || req.getRequestURI().endsWith("index.jsp")) {
            chain.doFilter(req, resp);
        } else {
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        }
    }

    @Override
    public void destroy() {
        // 过滤器销毁时执行的代码
        System.out.println("Filter destroyed");
    }
}